package leetcode;

import leetcode.entity.ListNode;

/**
 *
 * 1 -2-3-4-5-6
 * 1 1
 * 2 2
 * 3
 * @author:xufengxiang
 * @date 2023-04-11 20:06
 */
public class Code25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head ==null || head.next == null){
            return head;
        }

        boolean isEnd = false;
        //定义临时节点头，作为逆转后链表的头结点
        ListNode tmp = new ListNode();
        //移动节点，将tmp和每个 逆转后的k链表 连接起来
        ListNode p = tmp;
        //当前K链表的头
        ListNode curKHead;
        //下一个K链表的头
        ListNode nextKHead = head;

        while(!isEnd){
            int curCount = 0;
            while(head.next != null && curCount < k){
                curCount++;
                if(curCount == k){
                    //断开k链表和后续链表
                    ListNode q = head.next;
                    head.next = null;
                    head = q;
                }else {
                    head = head.next;
                }

            }
            //够K个
            if(curCount == k){
                curKHead = nextKHead;
                ListNode r = curKHead;
                p.next = swapPairs(curKHead);
                p = r;
                //记录下一个头
                nextKHead = head;
            }else{
                //不够K个
                isEnd = true;
                p.next = nextKHead;
            }
        }
        return tmp.next;
    }

    public ListNode swapPairs(ListNode head) {
        if(head ==null || head.next == null){
            return head;
        }

        ListNode tmp = new ListNode();
        ListNode p = tmp;
        ListNode next;
        while(head != null){
            next = head.next;
            head.next = p.next;
            p.next = head;
            head = next;
        }
        return tmp.next;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5,null);
        ListNode node4 = new ListNode(4,node5);
        ListNode node3 = new ListNode(3,node4);
        ListNode node2 = new ListNode(2,node3);
        ListNode node1 = new ListNode(1,node2);

        Code25 code25 = new Code25();
        code25.reverseKGroup(node1,3);
    }




}
